package com.goldman.aplt.util;

import com.goldman.aplt.base.type.TrxnEnvs;

import java.util.Optional;

/**
 * 上下文获取工具
 */
public class TrxnContext {


    private final ThreadLocal<TrxnEnvs> threadLocal;

    /**
     * 默认构造方法
     */
    private TrxnContext() {
        this.threadLocal = new ThreadLocal<>();
    }

    /**
     * 创建实例
     *
     * @return UserContextHolder单例
     */
    public static TrxnContext getInstance() {
        return SingletonHolder.sInstance;
    }

    /**
     * 静态内部类单例模式
     * 单例初使化
     */
    private static class SingletonHolder {
        /**
         * 使用静态变量返回单例
         */
        private static final TrxnContext sInstance = new TrxnContext();
    }
    public void setTrxnEnvs(TrxnEnvs trxnEnvs) {
        threadLocal.set(trxnEnvs);
    }
    /**
     * 获取上下文中的信息
     *
     * @return TrxnEnvs
     */
    public TrxnEnvs getTrxnEnvs() {
        return Optional.ofNullable(threadLocal.get()).orElse(new TrxnEnvs());
    }
    /**
     * 清空上下文
     */
    public void clear() {
        threadLocal.remove();
    }

}
